package dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dao.UserDao;
import entity.User;
import util.HibernateUtil;
import util.JsonUtil;

public class UserDaoImpl extends BaseDaoImpl<User, String> implements UserDao{
	private Session session;
	private void openSession(){
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		session = sessionFactory.openSession();
	}

	@Override
	public boolean exist(User user) {
		try{
			openSession();
			session.beginTransaction();
			String sql_str = "SELECT COUNT(1) FROM User u WHERE u.username=? AND u.password=?";
			Query query = session.createQuery(sql_str).setString(0, user.getUsername()).setString(1, user.getPassword());
			if((long)query.uniqueResult()>0){
				return true;
			}
			return false;
		}finally{
			session.close();
		}
	}

	@Override
	public String getAll(Map map) {
		try{
			openSession();
			session.beginTransaction();
			List<User> students = new ArrayList<User>();
			String sql_str = "FROM User";
			students = session.createQuery(sql_str).list();
			return JsonUtil.Array2Json(students);
		}finally{
			session.close();
		}
	}

}
